/*************************************************************************/
/* AJAX functions to get & put the statistique data in the data in table */
/*************************************************************************/

/*
* Index use to clean the table
*/
var idx     = 0;
var idxTab4 = 0;
var idxTab5 = 0;
var idxTab6 = 0;
var idxTab7 = 0;
var idxTab8 = 0;
var idxTab9 = 0;
var idxTab10 = 0;

$( "#consult" ).click(function() {
    $('#div_consult').show();
    $('#div_rater').hide();
});

$( "#rater" ).click(function() {
    $('#div_consult').hide();
    $('#div_rater').show();
});

function cleanResultTable(id)
{
    if (id == 1)
    {
        for (var i = 0; i < idx; i++) 
        {
            $('#result_line_' + i).remove();
        }
        idx = 0;
        $('#total_avg').remove();
        $('#title_result_avg_normal').remove();
    }
    else if (id == 2)
    {
        for (var i = 0; i < idxTab4; i++) {
            $('#line_stat_'+ i).remove();
        };
        idxTab4 = 0;
    }
    else if (id == 3)
    {
        for (var i = 0; i < idxTab5; i++) {
            $('#result_stat_5_' + i).remove();
        };
        idxTab5 = 0;
    }
    else if (id == 4)
    {
        for (var i = 0; i < idxTab6; i++) {
            $('#result_stat_6_' + i).remove();
        };
        idxTab6 = 0;   
    }
    else if (id == 5)
    {
        for (var i = 0; i < idxTab7; i++) {
            $('#result_line_7_' + i).remove();
        };
        idxTab7 = 0;    
    }
    else if (id == 6)
    {
        for (var i = 1; i < idxTab8; i++) {
            $('#id_rating_0' + i).remove();
        };

        for (var i = 0; i <= idxTab8; i++) {
            $('#criteria_mark_stat_8_' + i).remove();
        };

        idxTab8 = 0;
        idxTab9 = 0;
    }
    else if (id == 7)
    {
        for (var i = 0; i < idxTab10; i++) {
            $('#result_line_9_' + i).remove();
        };
        idxTab10 = 0;
    }
}

function isAllEmpty()
{
    idCountry       = $('#country').val();
    countryName     = $('#country option:selected').text();
    idGroup         = $('#group').val();
    groupName       = $('#group option:selected').text();
    team            = $('#team').val();
    nameRater       = $('#name_rater').val();

    if (idCountry == '' && idGroup == '' && team == '' && nameRater == '')
    {
        return true;
    }
    else
    {
        return false;
    }
}

function addColNormalMark()
{
    $('<th id="title_result_avg_normal">Note sur 20</th>').insertAfter('#title_result');
}

function generateTable(id_stat)
{
    var dateRange   = $('#daterange').val();
    var dateStart   = '';
    var dateEnd     = '';
    var calculType  = $('.btn.btn-default.btn-sm.active').attr('id');

    if (idx != 0)
    {
        cleanResultTable(1);
    }
    $('#loading_stat_1').show();
    if (dateRange != '')
    {
        result          = dateRange.split(' - ');
        dateStart       = result[0];
        dateEnd         = result[1];
        idCountry       = $('#country').val();
        countryName     = $('#country option:selected').text();
        idGroup         = $('#group').val();
        groupName       = $('#group option:selected').text();
        team            = $('#team').val();
        nameRater       = $('#name_rater').val();
        empty           = isAllEmpty();
        formId          = $('#name_form option:selected').val();

        $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    date_start  : dateStart, 
                    date_end    : dateEnd,
                    id_country  : idCountry,
                    id_group    : idGroup,
                    team        : team,
                    type        : calculType,
                    name_rater  : nameRater,
                    form_id     : formId
                }
            }).success(function(result) {
                var obj            = jQuery.parseJSON(result);
                //console.log(obj['third']);
                console.log(obj['query']);
                if ( obj.length != 0)
                {
                    $('#empty_table').hide();
                    if (typeof obj['first'] == 'undefined')
                    {
                    	$('#entire_table').show();
                        $('#table_stats').show();
                        $('#table_distribution').hide();

                        for (var row in obj)
                        {
                            if (row != 'total')
                            {
                                var copy = $('#result_line').clone();
                                copy.find('.daterange_table').text(dateRange);
                                
                                if (idCountry != '')
                                {
                                    copy.find('#country_table').text(obj[row]['name']);    
                                }
                                else
                                {
                                    if (typeof obj[row]['name'] == 'undefined' && empty == true)
                                    {
                                        copy.find('#country_table').text('All');       
                                    }
                                    else
                                    {
                                        copy.find('#country_table').text(obj[row]['name']);   
                                    }
                                }

                                if (idGroup != '')
                                {
                                    copy.find('#group_table').text(groupName);
                                }
                                else
                                {
                                    if (typeof obj[row]['groups'] == 'undefined' && empty == true)
                                    {
                                        copy.find('#group_table').text('All');       
                                    }
                                    else
                                    {
                                        copy.find('#group_table').text(obj[row]['groups']);
                                    }   
                                }

                                
                                if (typeof obj[row]['eval_name'] == 'undefined' && empty == true)
                                {
                                    copy.find('#eval_name').text('All');
                                }
                                else
                                {
                                    copy.find('#eval_name').text(obj[row]['eval_name']);
                                }   
                                
                                if (team != '')
                                {
                                    copy.find('#team_table').text(obj[row]['team']);    
                                }
                                else
                                {
                                    copy.find('#team_table').text('All');   
                                }

                                if (nameRater != '')
                                {
                                    copy.find('#name_rater_table').text(obj[row]['name_rater']);    
                                }
                                else
                                {
                                    copy.find('#name_rater_table').text('All');   
                                }

                                if (calculType == 'moy')
                                {
                                    $('#title_result').text('Moyenne des notes');
                                    var value = parseFloat(obj[row]['nb_rating']);
                                    total = (value * 20)/100;
                                    
                                    copy.append('<td>'+ total.toFixed(2) +'</td>');
                                    copy.find('#nb_eval_table').text(value.toFixed(2));
                                    
                                }
                                else
                                {
                                    $('#title_result').text("Nombre d'évaluation");
                                    copy.find('#nb_eval_table').text(obj[row]['nb_rating']);
                                }

                                copy.insertBefore('#before');
                                copy.attr('id', 'result_line_' + idx);
                                copy.show();

                                idx++;
                            }
                            else
                            {
                                var avg = parseFloat(obj[row]);
                                $("#total").text(avg);
                            }
                        }
                        if (calculType == 'moy')
                        {
                            addColNormalMark();
                            totalOnTwenty = (avg * 20) / 100;   
                            $('<td id="total_avg">'+ totalOnTwenty.toFixed(2) +'</td>').insertAfter('#total');
                        }
                    }
                    else 
                    {
                        $('#table_stats').hide();
                        $('#entire_table').hide();
                        $('#table_distribution').show();
                        $('#first_slice').text(obj['first']['count']);
                        $('#second_slice').text(obj['second']['count']);
                        $('#third_slice').text(obj['third']['count']);
                        $('#fourth_slice').text(obj['fourth']['count']);

                        $('#eval_form_1').text(obj['first']['eval_form']);
                        $('#eval_form_2').text(obj['second']['eval_form']);
                        $('#eval_form_3').text(obj['third']['eval_form']);
                        $('#eval_form_4').text(obj['fourth']['eval_form']);

                        $('.daterange_table').text(dateRange);
                        $('.country_name').text(countryName);
                        $('.group_name').text(groupName);
                        if (team != '')
                        {
                            $('.team').text(team);
                        }
                        else 
                        {
                            $('.team').text('All');
                        }
                        if (nameRater != '')
                        {
                            $('.name_rater').text(nameRater);    
                        }
                        else
                        {
                            $('.name_rater').text('All');
                        }
                    }
                }
                else
                {
                    $('#empty_table').show();
                    $('#table_stats').hide();
                    $('#entire_table').hide();
                }
                $('#loading_stat_1').hide();
            });
        $('#' + id_stat).show();
        $('#daterange_div').removeClass('has-error');
    }
    else
    {
        $('#daterange_div').addClass('has-error');
        $('#' + id_stat).hide();
    }
}

function generateTableNbRatingOver(id_stat)
{
    var dateRange   = $('#daterange_2').val();
    var dateStart   = '';
    var dateEnd     = '';
    var team        = $('#team_stat_2').val();
    
    $('#daterange_2_div').removeClass('has-error');
    $('#team_stat_2_div').removeClass('has-error');
    if (dateRange != '' && team != '')
    {
        result          = dateRange.split(' - ');
        dateStart       = result[0];
        dateEnd         = result[1];
        formId          = $('#name_form_stat_2 option:selected').val();
        
         $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type        : 'over_under',
                    date_start  : dateStart, 
                    date_end    : dateEnd,
                    form_id     : formId,
                    team        : team
                }
            }).success(function(result) {
                var obj = jQuery.parseJSON(result);
                var nb_over = parseInt(obj['over']['nb_rating']);
                var nb_under = parseInt(obj['under']['nb_rating'])
                var tot =  nb_under + nb_over;
                
                $('#nb_over').text(nb_over);
                $('#nb_under').text(nb_under);
                
                if (formId != '')
                {
                    $('#eval_form_under').text(obj['under']['eval_name']);
                    $('#eval_form_over').text(obj['over']['eval_name']);    
                }
                else
                {
                    $('#eval_form_under').text('All');
                    $('#eval_form_over').text('All');       
                }

                pr_over     = ((nb_over * 100) / tot);
                pr_under    = ((nb_under * 100) / tot);
                
                $('#nb_over_pr').text( (isNaN(pr_over.toFixed()) ? 0 : pr_over.toFixed()) + '%');
                $('#nb_under_pr').text( (isNaN(pr_under.toFixed()) ? 0 : pr_under.toFixed()) + '%');
                $('#loading_stat_2').hide();
            });
        $('#' + id_stat).show();   
    }
    if (dateRange == '')
    {
        $('#daterange_2_div').addClass('has-error');
    }
    if (team == '')
    {
        $('#team_stat_2_div').addClass('has-error');
    }
}

function generateTableAverage()
{
    var dateRange   = $('#daterange_3').val();
    var consultant  = $('#name_consultant_stats_3').val();
    var typeRequest = $('.btn.btn-default.btn-sm.type-request.active').attr('id');
    var result      = dateRange.split(' - ');
    var dateStart   = result[0];
    var dateEnd     = result[1];
    var formId      = $('#name_form_stat_3 option:selected').val();

    $('#daterange_3_div').removeClass('has-error');
    //à modifier pour mettre all dans le reporting de la table suivi des moyennes CC (Liste de toutes les notes !)
    if (dateRange != '' && consultant != '' && typeRequest == 'moy_consult')
    {
        $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_average',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    consultant_name : consultant,
                    form_id         : formId
                }
            }).success(function(result) {
                var obj = jQuery.parseJSON(result);
                
                if (typeof obj.length == 'undefined')
                {
                    $('#time_stats_3').text(dateRange);
                    $('#consultant_stats_3').text(consultant);
                    $('#average_mark').text(obj['consultant_mark']);
                    $('#average_mark_grp').text(obj['group_mark'] + ' ( ' + obj['group'] + ') ');
                }
                else
                {
                    $('#average_mark').text('Not found');
                    $('#average_mark_grp').text('Not Found');
                }
            });
        $('#result_stat_3_nb').hide();
        $('#result_stat_3').show();
    }

    if (dateRange != '' && consultant != '' && typeRequest == 'nb_consult')
    {
        $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_average_nb',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    consultant_name : consultant,
                    form_id         : formId
                }
            }).success(function(result) {
                var obj = jQuery.parseJSON(result);
                
                if (typeof obj[0]['nb_rating'] != 'undefined')
                {
                    $('#time_stats_3_nb').text(dateRange);
                    $('#consultant_stats_3_nb').text(consultant);
                    $('#number').text(obj[0]['nb_rating']);
                }
                else
                {
                    $('#number').text('Not found');
                }
                $('#result_stat_3_nb').show();
                $('#result_stat_3').hide();
            });
    }
    if (dateRange == '')
    {
        $('#daterange_3_div').addClass('has-error');
    }
}

function generateTableAverageMarkByCriteria()
{
    var dateRange   = $('#daterange_4').val();
    var consultant  = $('#name_consultant_stats_4').val();
    var group       = $('#group_stat_4').val();
    var country     = $('#country_stat_4').val();
    var countryName = $('#country_stat_4 option:selected').text();
    var teamRater   = $('#team_stat_4').val();
    var nameRater   = $('#name_rater_stat_4').val();
    var formId      = $('#name_form_stat_4').val();

    cleanResultTable(2);
    if (dateRange != '')
    {
        $('#daterange_4_div').removeClass('has-error');
        var result      = dateRange.split(' - ');
        var dateStart   = result[0];
        var dateEnd     = result[1];

        $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_average_criteria',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    id_group        : group,
                    consultant_name : consultant,
                    id_country      : country,
                    team            : teamRater,
                    name_rater      : nameRater,
                    form_id         : formId
                },
            beforeSend : function (xhr) {
                $('#loading_stat_4').show();
            }
            }).success(function(result) {
                var obj     = jQuery.parseJSON(result);

                if (obj.length != 0)
                {
                    for (var row in obj)
                    {
                        if (obj[row]['name'] != null)
                        {
                            copy    = $('#line_stat_').clone();
                            markCompressed = parseFloat(obj[row]['averageMark']);

                            copy.find('#form_name').text(obj[row]['name']);
                            copy.find('#criteria_name').text(obj[row]['criteriaName']);
                            copy.find('#mark').html(markCompressed.toFixed(2) + '<b> / 20</b>');
                            copy.find('#daterange').text(dateRange);

                            if (consultant != '')
                            {
                                copy.find('#consultant').text(obj[row]['consultantName']);    
                            }
                            else
                            {
                                copy.find('#consultant').text('All');
                            }

                            if (group != '')
                            {
                                copy.find('#group').text(obj[row]['groups']);
                            }
                            else
                            {
                                copy.find('#group').text('All');
                            }

                            if (country != '')
                            {
                                copy.find('#country').text(countryName);
                            }
                            else
                            {
                                copy.find('#country').text('All');   
                            }

                            if (teamRater != '')
                            {
                                copy.find('#team').text(obj[row]['team']);
                            }
                            else
                            {
                                copy.find('#team').text('All');   
                            }

                            if (nameRater != '')
                            {
                                copy.find('#name_rater').text(obj[row]['name_rater']);
                            }
                            else
                            {
                                copy.find('#name_rater').text('All');
                            }

                            copy.attr('id', 'line_stat_' + idxTab4);
                            copy.show();
                            copy.insertBefore('#line_stat_');
                            
                            idxTab4++;
                        }
                    }
                    $('#empty_table_stat_4').hide();
                    $('#result_stat_4').show();
                }
                else
                {
                    $('#result_stat_4').hide();       
                    $('#empty_table_stat_4').show();
                }
                $('#loading_stat_4').hide();
            });
    }
    else
    {
        $('#daterange_4_div').addClass('has-error');
    }
}

function generatableTableUnacceptable()
{
    var dateRange   = $('#daterange_5').val();
    var country     = $('#country_stat_5').val();
    var countryName = $('#country_stat_5 option:selected').text();
    var group       = $('#group_stat_5').val();
    var teamRater   = $('#team_stat_5').val();
    var nameRater   = $('#name_rater_stat_5').val();
    var consultant  = $('#name_consultant_stat_5').val();
    var formId      = $('#name_form_stat_5 option:selected').val();

    cleanResultTable(3);
    if (dateRange != '')
    {
        var result      = dateRange.split(' - ');
        var dateStart   = result[0];
        var dateEnd     = result[1];

        $('#loading_stat_5').show();
        $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_unacceptable',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    id_group        : group,
                    consultant_name : consultant,
                    id_country      : country,
                    team            : teamRater,
                    name_rater      : nameRater,
                    form_id         : formId
                }
            }).success(function(result) {
                var obj     = jQuery.parseJSON(result);

                if (obj.length != 0)
                {
                    for (var row in obj)
                    {
                        var copy = $('#result_stat_5_').clone();
                        copy.find('#time_stat_5').text(dateRange);

                        copy.find('#eval_name_stat_5').text(obj[row]['eval_name']);

                        if (country != '')
                        {
                            copy.find('#country_stat_5').text(countryName);
                        }
                        else
                        {
                            copy.find('#country_stat_5').text('All');
                        }

                        if (group != '')
                        {
                            copy.find('#group_stat_5').text(obj[row]['groups']);
                        }
                        else
                        {
                            copy.find('#group_stat_5').text('All');
                        }
                        if (teamRater != '')
                        {
                            copy.find('#team_stat_5').text(obj[row]['team']);
                        }
                        else
                        {
                            copy.find('#team_stat_5').text('All');
                        }
                        if (nameRater != '')
                        {
                            copy.find('#rater_stat_5').text(obj[row]['name_rater']);
                        }
                        else
                        {
                            copy.find('#rater_stat_5').text('All');
                        }
                        
                        if (consultant != '')
                        {
                            copy.find('#consultant_stat_5').text(obj[row]['name_consultant']);
                        }
                        else
                        {
                            copy.find('#consultant_stat_5').text('All');
                        }
                        
                        copy.find('#criteria_name_stat_5').text(obj[row]['criteriaName']);
                        copy.find('#nb_stat_5').text(obj[row]['nbUnacceptable']);

                        copy.attr('id', 'result_stat_5_' + idxTab5);
                        copy.show();
                        copy.insertBefore('#result_stat_5_');
                        idxTab5++;
                    }
                    $('#table_stat_5').show();
                    $('#empty_table_stat_5').hide();
                }
                else
                {
                    $('#empty_table_stat_5').show();
                    $('#table_stat_5').hide();
                }
                $('#loading_stat_5').hide();
            });
        $('#daterange_5_div').removeClass('has-error');
    }
    else
    {
        $('#daterange_5_div').addClass('has-error');
    }
}

function generateTableCalibration()
{
    var dateRange       = $('#daterange_6').val();
    var group           = $('#group_stat_6').val();
    var teamRater       = $('#team_stat_6').val();
    var nameRater       = $('#name_rater_stat_6 option:selected').text();

    if (nameRater == 'All') { 
        nameRater = '';
    }
    
    var id_nameRater    = $('#name_rater_stat_6').val();

    console.log(nameRater, id_nameRater);
    var result      = dateRange.split(' - ');
    var dateStart   = result[0];
    var dateEnd     = result[1];

    cleanResultTable(4);
    $('#result_stat_6_nb').hide();
    if (dateRange != '')
    {
        $.ajax({
        type: "GET",
        url: "statistics.php",
        data: {
                type            : 'table_calibration',
                date_start      : dateStart, 
                date_end        : dateEnd,
                id_group        : group,
                team            : teamRater,
                id_name_rater   : id_nameRater
            }
        }).success(function(result) {
            var obj = jQuery.parseJSON(result);
            
            if (obj.length != 0)
            {
                for (var row in obj)
                {
                    var copy = $('#result_stat_6_').clone();
                    copy.find('#time_stats_6_nb').text(dateRange);

                    copy.find('#group_stats_6_nb').text(obj[row]['groups']);
                    
                    copy.find('#team_stats_6').text(obj[row]['team']);
                    
                    if (nameRater != '')
                    {
                        copy.find('#name_rater_stats_6').text(obj[row]['firstname'] + ' ' + obj[row]['lastname']);
                    }
                    else
                    {
                        copy.find('#name_rater_stats_6').text('All');
                    }

                    copy.find('#nb_stats_6').text(obj[row]['nb_calibration']);
                    copy.attr('id', 'result_stat_6_' + idxTab6);
                    copy.show();
                    copy.insertBefore('#result_stat_6_');
                    idxTab6++;
                }
                $('#result_stat_6_nb').show();
                $('#empty_table_stat_6').hide();
            }
            else
            {
                $('#empty_table_stat_6').show();   
            }
        });
        $('#daterange_6_div').removeClass('has-error');
    }
    else
    {
        $('#daterange_6_div').addClass('has-error');
    }
}

/*
**   Do an average with the number in the data array
*/
function doAverage(data)
{
    var max     = data.length;
    var result  = 0;

    for (var i = max - 1; i >= 0; i--) {
        result += parseFloat(data[i]);
    };
    result = result / max;
    return result.toFixed(2);
}


/**
    Add all the number in the array data
*/
function doTotal(data)
{
    var total = 0;

    for (var i in data)
    {
        nb = data[i];
        total += parseInt(nb);
    }
    return total;
}

/**
*/

function generateListedConsultant()
{
    var dateRange   = $('#daterange_7').val();
    var teamRater   = $('#team_stat_7').val();
    var typeTeam    = $('.btn.btn-default.type-team.btn-sm.active').attr('id');
    var formId      = $('#name_form_stat_7 option:selected').val();
    var result      = dateRange.split(' - ');
    var dateStart   = result[0];
    var dateEnd     = result[1];

    var avgMarkTab  = [];
    console.log('form : ' + formId);
    cleanResultTable(5);
    $('#avg_rating_7').text('0');

    if (typeTeam == 'team')
    {
        if (dateRange != '' && teamRater != '')
        {
            $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_listed_consultant',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    team            : teamRater,
                    form_id         : formId
                },
            beforeSend : function (xhr) {
                $('#loading_stat_7').show();
            }
            }).success(function(result) {

                var obj = jQuery.parseJSON(result);
                //console.log(obj['query']);

                if (obj.length != 0)
                {
                    for (var row in obj)
                    {
                        var copy = $('#result_line_7_').clone();
                        
                        copy.find('#name_consultant').text(obj[row]['name_consultant']);
                        copy.find('#mark_and_average').text(obj[row]['final_mark']);
                        copy.find('#id_rating').html('<a target="_blank" href="show_rating.php?id='+obj[row]['id'] +'">'+ obj[row]['id'] +'</a>');
                        copy.find('#date').text(obj[row]['date_eval']);
                        copy.find('#name_rater').text(obj[row]['name_rater']);


                        copy.attr('id', 'result_line_7_' + idxTab7);
                        copy.show();
                        copy.insertBefore('#result_line_7_');
                        avgMarkTab.push(obj[row]['final_mark']);
                        idxTab7++;
                    }
                    $('#avg_rating_7').text(doAverage(avgMarkTab));
                }
                $('#time_lapse').text(dateRange);
                $('#team_7').text(teamRater);
                $('#nb_rating_7').text(obj.length);
                $('#result_stat_7_nb').show();
                $('#loading_stat_7').hide();
            });
            $('#daterange_7_div').removeClass('has-error');
        }
        else
        {
            $('#daterange_7_div').addClass('has-error');
        }
    }
    else
    {
        var groupSelected       = $('#group_stat_7').val();
        var groupNameSelected   = $('#group_stat_7 option:selected').text();
        
        if (dateRange != '' && teamRater != '')
        {
            $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_listed_consultant',
                    date_start      : dateStart, 
                    date_end        : dateEnd,
                    id_group        : groupSelected
                },
            beforeSend : function (xhr) {
                $('#loading_stat_7').show();
            }
            }).success(function(result) {
                var obj = jQuery.parseJSON(result);
                
                console.log(obj.length);
                if (obj.length != 0)
                {
                    for (var row in obj)
                    {
                        var copy = $('#result_line_7_').clone();
                        
                        copy.find('#name_consultant').text(obj[row]['name_consultant']);
                        copy.find('#mark_and_average').text(obj[row]['final_mark']);
                        copy.find('#id_rating').html('<a target="_blank" href="show_rating.php?id='+ obj[row]['id'] +'">'+ obj[row]['id'] +'</a>');
                        copy.find('#date').text(obj[row]['date_eval']);
                        
                        avgMarkTab.push(obj[row]['final_mark']);
                        copy.attr('id', 'result_line_7_' + idxTab7);
                        copy.show();
                        copy.insertBefore('#result_line_7_');
                        idxTab7++;
                    }
                    $('#avg_rating_7').text(doAverage(avgMarkTab));
                }
                else
                {
                    console.log(obj);
                }

                $('#time_lapse').text(dateRange);
                $('#team_7').text(groupNameSelected);
                $('#nb_rating_7').text(obj.length);
                $('#result_stat_7_nb').show();
                $('#loading_stat_7').hide();
            });
            $('#daterange_7_div').removeClass('has-error');
        }
        else
        {
            $('#daterange_7_div').addClass('has-error');
        }
    }
}

/**
    Display gap between Criteria
*/
function calculateGap(maxEval, maxCrit)
{
    var strHtmlTwenty  = '';
    var strHtmlGap     = '';

    for (var j = 0; j < maxCrit; j++)
    {
        var tab = [];
        for (var i = maxEval - 1; i >= 0; i--) {
            tab.push($('#mark_' + i + '_'+ j).text());
        };

        var max = Math.max.apply(Math, tab);
        var min = Math.min.apply(Math, tab);
        var gap = max - min;

        strHtmlTwenty   += '<td>' + parseFloat(gap) + '</td>';
        strHtmlGap      += '<td>' + ((parseFloat(gap) * 100) / 20) + '</td>'
    }
    $('#gap_on_twenty').html('<td><b>Ecart ( /20 )</b></td>' + strHtmlTwenty);
    $('#gap').html('<td><b>Ecart ( % )</b></td>' + strHtmlGap);
}


/*
** Display the rating list with the mark associate with the calibration
*/
function generateCriteriaTableByCalibration()
{
    var idCali = $('#calibration_8 option:selected').val();
    var listed  = [];
    
    cleanResultTable(6);
    $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_criteria_title',
                    id_calibration  : idCali
                }
            }).success(function(result) {
                var obj     = jQuery.parseJSON(result);
                var i       = 0;
                var maxCrit = obj.length;

                for (var row in obj)
                {
                    if (i == 0)
                    {
                       $('#id_rating_0').html('<b>' + obj[row]['name'] + '</b> ( /20 )');
                    }
                    else 
                    {
                        var copy = $('#id_rating_0').clone();

                        copy.html('<b>' + obj[row]['name'] + '</b> ( /20 )');
                        copy.attr('id', 'id_rating_0' + i);

                        copy.insertBefore('#beforeThis');
                    }
                    listed.push(obj[row]['name']);
                    i++;
                }

                idxTab8 = i;
                $.ajax({
                    type: "GET",
                    url: "statistics.php",
                    data: {
                            type            : 'table_criteria_description',
                            id_calibration  : idCali
                        }
                    }).success(function(result) {
                        var obj     = jQuery.parseJSON(result);
                        var maxEval = obj.length;

                        for (var row in obj)
                        {
                            var copy    = $('#criteria_mark_stat_8').clone();
                            htmlStr     = '<td>' + obj[row][0]['id_rating'] + '</td>';

                            for (var line in obj[row])
                            {
                                htmlStr += '<td id="mark_'+ row +'_'+ line +'">' + obj[row][line]['mark'] + '</td>';
                            }
                            
                            copy.html(htmlStr);
                            copy.attr('id', 'criteria_mark_stat_8_' + idxTab9);
                            copy.insertBefore('#gap_on_twenty');
                            idxTab9++;
                        }
                        calculateGap(maxEval, maxCrit);
                    });
                    $('#criteriaByCalibration').show();
            });
}

function generateTableDebrief()
{
    var idManager       = $('#team_stat_9 option:selected').val();
    var idGroup         = $('#group_stat_9 option:selected').val();
    var groupName       = $('#group_stat_9 option:selected').text();
    var dateRange       = $('#daterange_9').val();
    var result          = dateRange.split(' - ');
    var dateStart       = result[0];
    var dateEnd         = result[1];
    var totalRejected   = [];
    var totalValidated  = [];
    var total           = [];

    cleanResultTable(7);
    $.ajax({
            type: "GET",
            url: "statistics.php",
            data: {
                    type            : 'table_debrief',
                    id_group        : idGroup,
                    date_start      : dateStart,
                    date_end        : dateEnd
                }
            }).success(function(result) {
                var obj = jQuery.parseJSON(result);
                
                if (obj.length != 0)
                {
                    for (var row in obj)
                    {
                        var copy = $('#result_line_9_').clone();

                        copy.find('#time_lapse').text(dateRange);
                        copy.find('#group').text(obj[row]['grp']);
                        copy.find('#name_rater').text(obj[row]['firstname_rater'] + ' ' + obj[row]['lastname_rater']);
                        copy.find('#nb_debrief_rejected').text(obj[row]['nb_rating_rejected']);
                        copy.find('#nb_debrief_validated').text(obj[row]['nb_rating_validated']);
                        copy.find('#nb_total_debrief').text(obj[row]['total_debrief']);

                        totalRejected.push(obj[row]['nb_rating_rejected']);
                        totalValidated.push(obj[row]['nb_rating_validated']);
                        total.push(obj[row]['total_debrief']);

                        copy.attr('id', 'result_line_9_'+ idxTab10);
                        copy.show();
                        copy.insertBefore('#totals');
                        idxTab10++;
                    }    
                    
                    $('#total_rejected').text(doTotal(totalRejected));
                    $('#total_validated').text(doTotal(totalValidated));
                    $('#total_total').text(doTotal(total));
                    $('#empty_table_stat_9').hide();
                    $('#result_stat_9_nb').show();
                }
                else
                {
                    $('#empty_table_stat_9').show();
                    $('#result_stat_9_nb').hide();
                }
                
            });
}